package yannan.voiplock4ble.utils;

import android.util.Log;

import com.yongchun.library.BuildConfig;

import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.CommonResponse;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.LockKeyBean;
import yannan.voiplock4ble.bean.LockKeyBeanDao;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.MyDBHelper;
import yannan.voiplock4ble.db.daomanager.LockKeyDaoManager;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;

/**
 * 说明：和操作门锁相关的工具类
 * 作者：mainTel
 * 时间：2016/12/7 15:53
 * 备注：
 */
public class OperLockUtils {


    public final static int EDITLOCKUSERINFO_DEL = 2;
    public final static int EDITLOCKUSERINFO_CHANGE_ADMIN = 0;
    public final static int EDITLOCKUSERINFO_CHANGE_COMMON = 1;
    public final static int EDITLOCKUSERINFO_BAN = 3;
    public final static int EDITLOCKUSERINFO_ALLOW = 4;

    /**
     * 绑定门锁
     *
     * @param lockBean
     * @param i        如果绑定失败 重试次数
     */
    public static void bindLock(final LockBean lockBean, final int i) {

        if (MyApplication.getInterface().userBean != null)
            NetUtils.getNetworkService().bindLockUrl(lockBean.lockserialId, MyApplication.getInterface().userBean.userId,
                    lockBean.userPermission + "", lockBean.lockName, lockBean.mac).enqueue(new NetworkCallBack<CommonResponse>() {
                @Override
                public void onSuc(CommonResponse resBody) {
                    if (resBody != null) {
                        if (resBody.returnValue.equals("1")) {
                            uploadOperation(lockBean.lockserialId, "绑定了门锁", "2", TimeUtils.getNowTimeyMdHMS());
                        }
                    }
                }

                @Override
                public void onFail(String msg) {
                    //是否应该重新绑定？ 重试5次
                    int x = i;
                    if (x <= 5) {
                        bindLock(lockBean, ++x);
                    }
                }
            });
    }

    /**
     * 上传门锁地址
     *
     * @param lockserialId
     * @param address
     * @param lal
     */
    public static void upLoadLockAddress(final String lockserialId, final String address, final String lal) {
        if (MyApplication.getInterface().userBean != null) {
            NetUtils.getNetworkService().uploadAddress(MyApplication.getInterface().userBean.userId,
                    lockserialId, address, lal).enqueue(new NetworkCallBack<CommonResponse>() {
                @Override
                public void onSuc(CommonResponse resBody) {

                }

                @Override
                public void onFail(String msg) {
                    //上传失败，重新上传
//                    upLoadLockAddress(lockserialId, address, lal);
                }
            });
        }
    }

    /**
     * 上传操作日志
     *
     * @param lockserialId     锁的序列号
     * @param operationDetails 操作内容
     */
    public static void uploadOperation(final String lockserialId, String operationDetails, final String type, String time) {

        if (MyApplication.getInterface().userBean != null)
            NetUtils.getNetworkService().uploadOperation(MyApplication.getInterface().userBean.userId,
                    time, operationDetails, type, lockserialId)
                    .enqueue(new NetworkCallBack<CommonResponse>() {
                        @Override
                        public void onSuc(CommonResponse resBody) {

                        }

                        @Override
                        public void onFail(String msg) {
                        }
                    });
    }

    /**
     * 修改门锁钥匙（指静脉、密码）
     *
     * @param bean          LockKeyBean
     * @param operationType 操作类型 {@link #EDITLOCKUSERINFO_DEL},
     */
    public static void editLockKey(final LockKeyBean bean, final int operationType) {
        NetUtils.getNetworkService().editLockUserInfo(bean.lockserialId,
                bean.type, bean.userIdentifier, operationType + "")
                .enqueue(new NetworkCallBack<CommonResponse>() {
                    @Override
                    public void onSuc(CommonResponse resBody) {
                        String key = "指静脉";
                        if (resBody.returnValue != null) {
                            MyDBHelper.upDateLocalTime(bean.lockserialId, resBody.returnValue, bean.type);
                            if (bean.type.equals("1"))
                                key = "密码";
                            switch (operationType) {
                                case EDITLOCKUSERINFO_DEL:
                                    uploadOperation(bean.lockserialId, "删除了" + key + bean.userIdentifier, bean.type, resBody.returnValue);
                                    break;
                                case EDITLOCKUSERINFO_BAN:
                                    uploadOperation(bean.lockserialId, "禁用了" + key + bean.userIdentifier, bean.type, resBody.returnValue);
                                    break;
                                case EDITLOCKUSERINFO_ALLOW:
                                    uploadOperation(bean.lockserialId, "将" + key + bean.userIdentifier + "解除禁用", bean.type, resBody.returnValue);
                                    break;
                                case EDITLOCKUSERINFO_CHANGE_ADMIN:
                                    uploadOperation(bean.lockserialId, "将" + key + bean.userIdentifier + "设置为管理员", bean.type, resBody.returnValue);
                                    break;
                                case EDITLOCKUSERINFO_CHANGE_COMMON:
                                    uploadOperation(bean.lockserialId, "将" + key + bean.userIdentifier + "设置为普通用户", bean.type, resBody.returnValue);
                                    break;
                            }

                        }
                    }

                    @Override
                    public void onFail(String msg) {
                        if (BuildConfig.DEBUG)
                            Log.e("OperLockUtils", msg);
                    }
                });
    }

    public static void banPickLockKeyResult(LockKeyBean operKeyBean) {
        try {
            LockKeyBean key = DaoUtils.getDao(LockKeyDaoManager.class).getQueryBuilder().where(
                    LockKeyBeanDao.Properties.UserIdentifier.eq(operKeyBean.userIdentifier)
            ).build().list().get(0);
            if (key.isBan.equals("0")) {
                key.isBan = "1";
                OperLockUtils.editLockKey(operKeyBean, OperLockUtils.EDITLOCKUSERINFO_ALLOW);
            } else {
                key.isBan = "0";
                OperLockUtils.editLockKey(operKeyBean, OperLockUtils.EDITLOCKUSERINFO_BAN);
            }
            DaoUtils.getDao(LockKeyDaoManager.class).insertOrReplace(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void delLockKeyResult(LockKeyBean operKeyBean) {
        try {
            LockKeyBean key = DaoUtils.getDao(LockKeyDaoManager.class).getQueryBuilder().where(
                    LockKeyBeanDao.Properties.UserIdentifier.eq(operKeyBean.userIdentifier)
            ).build().list().get(0);
            DaoUtils.getDao(LockKeyDaoManager.class).delete(key);
            OperLockUtils.editLockKey(operKeyBean, OperLockUtils.EDITLOCKUSERINFO_DEL);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void changeKeyAdmin(LockKeyBean operKeyBean) {
        try {
            LockKeyBean key = MyDBHelper.getLockKeyBeanByID(operKeyBean.lockserialId, operKeyBean.userIdentifier);
            if (key.userPermission.equals("0")) {
                key.userPermission = "1";
                OperLockUtils.editLockKey(operKeyBean, OperLockUtils.EDITLOCKUSERINFO_CHANGE_ADMIN);
            } else {
                key.userPermission = "0";
                OperLockUtils.editLockKey(operKeyBean, OperLockUtils.EDITLOCKUSERINFO_CHANGE_COMMON);
            }
            DaoUtils.getDao(LockKeyDaoManager.class).insertOrReplace(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void editKeyRemarks(LockKeyBean bean, String msg) {
        try {
            LockKeyBean key = MyDBHelper.getLockKeyBeanByID(bean.lockserialId, bean.userIdentifier);
            key.nickName = msg;
            DaoUtils.getDao(LockKeyDaoManager.class).insertOrReplace(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
